<?php

namespace app\common;

use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class TableComment extends Command
{
    protected function configure()
    {
        $this->setName('table_comment')
            ->setDescription('生成表数据的备注文件');
    }

    protected function execute(Input $input, Output $output)
    {
        $prefix = Config::get('database.prefix');
        $db = Config::get('database.database');

        $tables = Db::query("select TABLE_NAME from information_schema.tables where TABLE_SCHEMA = \"{$db}\"");
        $tablesName = [];
        foreach ($tables as $table) {
            $tablesName[$table['TABLE_NAME']] = str_replace($prefix, '',$table['TABLE_NAME']);
        }
        if (empty($tablesName)) {
            $this->output('table null');
            exit;
        }
        $path = APP_PATH . DS . 'common' .DS . 'lang' . DS . 'table-comment';
        if (!file_exists($path)){
            @mkdir($path);
        }

        foreach ($tables as $table) {
            $fieldsInfo = Db::query('SHOW FULL COLUMNS FROM ' . $table['TABLE_NAME']);
            $comments = [];
            foreach ($fieldsInfo as $value) {
                $comments[$value['Field']] = $value['Comment'];
            }
            $fileName = $path . DS . $tablesName[$table['TABLE_NAME']] . ".php";
            @touch($fileName);
            $content = "<?php\n";
            $content .= "return [\n";
            foreach ($comments as $field => $comment){
                if (empty($comment)) {
                    continue;
                }
                $content .= "\t\"{$field}\" => \"{$comment}\",\n";
            }
            $content .= "];";
            file_put_contents($fileName, $content);
        }


        $output->info("Build Successed!");
    }

}